var Dudu=(function(){
var chinese = /^[\u4E00-\u9FFF]+$/;
var hasOwn=Object.prototype.hasOwnProperty;
/**  
 * 联系人
 */
function Contact(name, telephone) {
  this.name = name.toLowerCase();
  this.telephone = telephone;
//  this.html = '<div class="nomail" name="'+name+'" tel="'+telephone+'"><dt>' + name.charAt(0) + '</dt><dd><b>' + name + '</b><span>' + telephone+'</span></dd><i><img name="dialentry" src="images/phone_icon.png" width="20" height="20" tel="'+telephone+'" called="'+name+'"></i></div>';
  this.html = '<div class="nomail" name="'+name+'" tel="'+telephone+'"><dt>' + name.charAt(0) + '</dt><dd><b>' + name + '</b><span>' + telephone+'</span></dd><i class="iconfont" name="dialentry" tel="'+telephone+'" called="'+name+'">&#xe608;</i><strong class="iconfont">&#xe611;</strong></div>';
  this.chinese = true;
  if (chinese.test(name)) { 
    var r = cc2phonetic(name);   
    if (r && r.length == 2) {  
      this.phonetic = r[0];
      this.flphonetic = r[1];
    }
  } else {
    this.chinese = false;
  }
}

Contact.prototype = {
  toString : function() {
    return this.html;
  },
  matchName : function(search) {
    return this.name.indexOf(search) > -1;
  },
  matchTelphone : function(search) {
    return this.telephone.indexOf(search) > -1;
  },
  matchChinesePhonetic : function(search) {
    if (this.chinese) {
      return this.phonetic.indexOf(search) > -1 || this.flphonetic.indexOf(search) > -1;
    } else
      return false;
  }
}

/**
 * 电话簿
 */
function Directory(context, type, searchContext,selectContacts,caller,maxSize) {   
  this.context = context;
  this.type = type || this.defaultType;
  this.contacts = [];
  this.htmls = [];  
  this.show = false;//是否显示
  this.parent=this.context.parent();
  this.caller=caller;//主叫信息
  this.searchContext=searchContext;//号码簿搜索结果展示区域
  this.conferenceNumbers=(selectContacts&&selectContacts.data)||{};//已选择参会号码,号码散列表
  this.count=(selectContacts&&selectContacts.size)||0;
  this.maxSize=(maxSize&&maxSize>0)?maxSize:0;//最大加载通讯录数量，用于分页
  this.last=-1;
}

Directory.prototype = {
  defaultType : 'company',
  addContact : function(name, telephone) {
  	if(telephone===this.caller.caller)//过滤掉主叫号码，不在通讯录里显示
  		return this;
    var contact = new Contact(name, telephone);
    this.contacts.push(contact);
    if(this.alreadyAdd(telephone)){
        this.htmls.push(contact.html.replace('nomail','nomail checkboxd').replace('&#xe611','&#xe610'));
    } 
    else
      this.htmls.push(contact.html);
    return this;
  },
  create : function(param) {
    if(this.maxSize>0){
      this.context.html(this.htmls.slice(0,this.maxSize).join(''));
    }else
      this.context.html(this.htmls.join(''));
    var caller=this.caller.caller,type=this.type;
	$(document.body).on('click','i[name="dialentry"]',function(event){
		if(param.dial){
			var $this=$(this);
			param.dial({
				caller:caller,
				called:$this.attr('tel'),   
				calledName:$this.attr('called'),
				calledType:type
			});
		}
		event.stopPropagation();
	});  
    return this;
  },
  getContext:function(){
	return this.context;
  },
  reload:function(text,callback){
    this.show=false;
    this.create().select(text,callback);
  },
  next:function(search,callback){
    var ct = this.contacts;
    if(this.last<ct.length-1){
      var result = []; 
      if(!search){
        var ct = this.contacts,
        surplus=ct.length-(this.last+1),
        l=(this.last+1)+Math.min(this.maxSize,surplus);
        for (var i = (this.last+1); i < l; i++) {
          if(this.hasAdded()){
            this.checkedHightlights(result,ct[i].html,ct[i].telephone);
          }else
            result.push(ct[i].html);
        }
        this.last=i-1;
        this.context.append(result.join(''));
        if(callback&&(typeof callback)==='function')
            callback.apply(this.context,[search,result]);
      }else{
        var c=0;
    	search=search.toLowerCase();
        for (var i = (this.last+1); i < ct.length; i++) {
          if (ct[i].matchName(search) || ct[i].matchTelphone(search) || ct[i].matchChinesePhonetic(search)) {
              if(this.hasAdded()){
                this.checkedHightlights(result,ct[i].html,ct[i].telephone);
              }else
                result.push(ct[i].html);
              if(this.maxSize<=++c){//匹配到的通讯录数量已经达到最大容量
                this.last=i;
                break;
              }        
          }
        }
        if(i===ct.length){//已经匹配到通讯录结尾
          this.last=i-1;
        }    
        this.searchContext.append(result.join(''));
      if(callback&&(typeof callback)==='function')
          callback.apply(this.searchContext,[search,result]);
      }
      return (result.length>0);
    }
    return false;
  },
  search : function(search,callback) {
    if(!search){
      var ct = this.contacts;
      var result = [],l=(this.maxSize>0)?Math.min(this.maxSize,ct.length):ct.length;
      this.last=l-1;
      if(this.hasAdded()){//有选中的号码
        for (var i = 0; i < l; i++) {
           this.checkedHightlights(result,ct[i].html,ct[i].telephone);
        }
        this.context.html(result.join(''));
      }
      this.context.css('display','');
      this.searchContext.css('display','none');
	  if(callback&&(typeof callback)==='function')
        callback.apply(this.context,[search,result]);
    }else{
      var ct = this.contacts;
      var result = [],c=0;
      search=search.toLowerCase();
      for (var i = 0; i < ct.length; i++) {
        if (ct[i].matchName(search) || ct[i].matchTelphone(search) || ct[i].matchChinesePhonetic(search)) {
            if(this.hasAdded()){
              this.checkedHightlights(result,ct[i].html,ct[i].telephone);
            }else
              result.push(ct[i].html);
            if(this.maxSize>0&&this.maxSize<=++c){//匹配到的通讯录数量已经达到最大容量
              this.last=i;
              break;
            }        
        }
      }
      if(this.maxSize>0&&i===ct.length){//已经匹配到通讯录结尾
        this.last=i-1;
      }    
      this.searchContext.html(result.join(''));
      this.searchContext.css('display','');
      this.context.css('display','none');
	  if(callback&&(typeof callback)==='function')
        callback.apply(this.searchContext,[search,result]);
    }
  },
  checkedHightlights:function(rc,html,tel){
    if(hasOwn.call(this.conferenceNumbers, tel)){
      rc.push(html.replace('nomail','nomail checkboxd').replace('&#xe611','&#xe610'));
    }else 
      rc.push(html);
  },
  selectAll:function(handler){
	  var display=this.context.css('display'),content=this.context;
	  if(display==='none')
		  content=this.searchContext;
	  var th=this;
	  var k=0;
	  var l=content.find('div[class="nomail checkboxd"]').length;//当前已经选择的记录
	  content.find('div[class="nomail"]').each(function(i,elem){
		  var obj=$(this);
		  if(typeof handler==='function'&&!handler(k+1,obj,l))
            return false; 
		  k++;
		  var tel=obj.attr('tel');
    	  th.addConference(obj.attr('name'), tel);  
    	  obj.addClass('checkboxd');
		  $(this).find('strong').html('&#xe610;');
	  });
	  return k+l;
  },
  unselectAll:function(){
	  var display=this.context.css('display'),content=this.context;
	  if(display==='none')
		  content=this.searchContext;
	  var th=this;
	  content.find('div').each(function(i,elem){
		  var obj=$(this);
		  var tel=obj.attr('tel');
		  if(th.alreadyAdd(tel)){
	    	  th.removeConference(obj.attr('name'), tel);  
	    	  obj.removeClass('checkboxd');
  			  $(this).find('strong').html('&#xe611;');
		  }
	  });
  },
  select : function(text,callback) {
    if(!this.show){
      this.show = true;
      this.search(text,callback);
      this.parent.addClass('current');
    }
    return this;
  },
  unselect : function() {  
    if(this.show){
      this.show = false;
      this.parent.removeClass('current');
      this.searchContext.css('display','none');
      this.context.css('display','none');
    }
  },
  reset:function(){
    this.last=-1;
    return this;
  },
  isSelected : function() {
    return this.show;
  },
  addConference :function(name,tel){
    if(!this.alreadyAdd(tel)){
      this.conferenceNumbers[tel]=name;
      this.count++;
      return true;
    } 
    return false;
  },
  removeConference:function(name,tel){
    if(this.alreadyAdd(tel)){
      delete this.conferenceNumbers[tel];
      this.count--;
      return true;
    }
    return false;
  },
  getSelectedSize:function(){
	  return this.count;
  },
  hasAdded:function(){
    return  this.count>0;
  },
  alreadyAdd:function(tel){
    return hasOwn.call(this.conferenceNumbers, tel);
  },
  hasContacts:function(){   
    return this.contacts.length>0;
  },
  getAddedContacts:function(){
    var rc=[];
    for(var tel in this.conferenceNumbers){ 
      var s={name:this.conferenceNumbers[tel],telephone:tel,type:this.type};
      rc.push(s);
    }  
    return rc;   
  },
  destroy:function(){  
    this.context=null;
    this.conferenceNumbers=null;
    this.contacts=null;
    this.parent=null;
    this.searchContext=null;  
  },
  contains:function(tel){
    var ct=this.contacts;
    for (var i = 0; i < ct.length; i++) {
      if (ct[i].telephone==tel) {
         return true;
      }
    } 
    return false;
  }
};
return {
  Directory:Directory
};
})();


